//support.js
class Container {
  static of (value) {
    return new Container(value)
  }
  constructor(value) {
    this._value = value
  }
  map (fn) {
    return Container.of(fn(this._value))
  }
}
class Maybe {
  static of (x) {
    return new Maybe(x)
  }
  isNothing () {
    return this._value === null || this._value === undefined
  }
  constructor(x) {
    this._value = x
  }
  map (fn) {
    return this.isNothing() ? this : Maybe.of(fn(this._value))
  }
}
// 练习一
const fp = require('lodash/fp')
let maybe = Maybe.of([5, 6, 1])
let ex1 = () => {
  return function (maybe) {
    let newMaybe;
    maybe.map(item => newMaybe = Maybe.of(fp.map(x => fp.add(x, 1))(item)))
    return newMaybe
  }
}
console.log(ex1()(maybe)) 
// 练习二
let xs = Container.of(['do', 'ray', 'me', 'fa', 'so', 'la', 'it', 'do'])
let ex2 = () => {
  return function (xs) {
    let newMaybe;
    // maybe.map(item => newMaybe = Container.of(fp.first(item)))
    maybe.map(item => newMaybe = fp.first(item))
    return newMaybe
  }
}
console.log(ex2()(xs)) 
//练习3，使用safeProp和fp.first找到user的名字的首字母
let  safeProp=fp.curry(function(x,o){
  return Maybe.of(o[x])
})
let user = {id:2,name:'Albert'}
let ex3 = ()=>{
  return function (user) {
    let newMaybe;
    safeProp('name', user).map(x => newMaybe=fp.first(x))
    return newMaybe
  }
}
console.log(ex3()(user)) 
//练习4，重写ex4,不要有if语句
let ex4=function(n){
  if(n){
    return parseInt(n)
  }
}
//重写
let newEx4 = n=>{
  let item;
  Maybe.of(n).map(x => item = parseInt(x))
  return item
}
console.log(newEx4(4.5))

